package com.neusoft.zqygbc.neusoft_wenda.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jaiky.imagespickers.Image;
import com.neusoft.zqygbc.neusoft_wenda.R;
import com.neusoft.zqygbc.neusoft_wenda.base.RetrofitCallback;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.Question;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.QuestionEntity;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.Status;
import com.neusoft.zqygbc.neusoft_wenda.model.AnswerModel;
import com.neusoft.zqygbc.neusoft_wenda.model.QusetionModel;
import com.neusoft.zqygbc.neusoft_wenda.utils.AudioRecoderUtils;
import com.neusoft.zqygbc.neusoft_wenda.utils.MapUtils;
import com.neusoft.zqygbc.neusoft_wenda.utils.PopupWindowFactory;
import com.neusoft.zqygbc.neusoft_wenda.utils.TimeUtils;

import java.io.File;

import retrofit2.Call;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

public class AnswerActivity extends CheckPermissionsActivity {
    private SharedPreferences sp;
    private ImageView answer_return;
    private TextView answer_description;
    private TextView answer_textcontent;
    private EditText answer_content;
    private ImageView answer_voice;
    private ImageView answer_location;
    private TextView answer_locationtext;
    private ImageView answer_send;
    private Intent intent;
    private QusetionModel qusetionModel;
    private Call call;
    private RetrofitCallback<Question> questionCallback;
    private AnswerModel answerModel;
    private RetrofitCallback<Status> answerCallback;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private String qid;


    static final int VOICE_REQUEST_CODE = 66;
    private ImageView iv_recording_icon;
    private TextView tv_recording_time;
    private AudioRecoderUtils mAudioRecoderUtils;
    private LinearLayout rl;
    private PopupWindowFactory mPop;
    private Context context;
    private Button answer_paly;


    private String voice_filePath;
    private MediaPlayer player;
    private boolean isPause = false;
    private File file;
    private boolean isVisible = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer);

        context = this;
        rl = (LinearLayout) findViewById(R.id.answer_lr);
        answer_voice = (ImageView) findViewById(R.id.answer_voice);
        //PopupWindow的布局文件
        final View view = View.inflate(this, R.layout.layout_microphone, null);
        mPop = new PopupWindowFactory(this, view);
        //PopupWindow布局文件里面的控件
        iv_recording_icon = (ImageView) view.findViewById(R.id.iv_recording_icon);
        tv_recording_time = (TextView) view.findViewById(R.id.tv_recording_time);

        mAudioRecoderUtils = new AudioRecoderUtils();
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {

            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
                iv_recording_icon.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
                tv_recording_time.setText(TimeUtils.long2String(time));
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
                Toast.makeText(AnswerActivity.this, "录音保存在：" + filePath, Toast.LENGTH_SHORT).show();
                voice_filePath = filePath;
                tv_recording_time.setText(TimeUtils.long2String(0));
            }
        });

        //6.0以上需要权限申请
        requestPermissions();


        initViews();
        initData();
        initEvents();
        //初始化定位
        initLocation();
    }

    /**
     * 开启扫描之前判断权限是否打开
     */
    private void requestPermissions() {
        //判断是否开启摄像头权限
        if ((ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
                (ContextCompat.checkSelfPermission(context,
                        Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
                ) {
            StartListener();

            //判断是否开启语音权限
        } else {
            //请求获取摄像头权限
            ActivityCompat.requestPermissions((Activity) context,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, VOICE_REQUEST_CODE);
        }

    }

    /**
     * 请求权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == VOICE_REQUEST_CODE) {
            if ((grantResults[0] == PackageManager.PERMISSION_GRANTED) && (grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                StartListener();
            } else {
                Toast.makeText(context, "已拒绝权限！", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public void StartListener() {
        //Button的touch监听
        answer_voice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:

                        mPop.showAtLocation(rl, Gravity.CENTER, 0, 0);


                        mAudioRecoderUtils.startRecord();


                        break;

                    case MotionEvent.ACTION_UP:

                        mAudioRecoderUtils.stopRecord();        //结束录音（保存录音文件）
//                        mAudioRecoderUtils.cancelRecord();    //取消录音（不保存录音文件）
                        mPop.dismiss();
                        display();

                        break;
                }
                return true;
            }
        });
    }

    private void display() {
        if (isVisible) {
            isVisible = false;
            answer_paly.setVisibility(View.VISIBLE);//这一句显示布局LinearLayout区域
        } else {
            answer_paly.setVisibility(View.GONE);//这一句即隐藏布局LinearLayout区域
            isVisible = true;
        }

    }

    private void initData() {
        qusetionModel = new QusetionModel();
        call = qusetionModel.getQuestionDetail(intent.getStringExtra("qid"));
        questionCallback = new RetrofitCallback<Question>() {
            @Override
            public void onResponse(Question question) {
                QuestionEntity questionEntity = question.getQuestionDetail().getQuestion();
                answer_description.setText(questionEntity.getDescription());
                answer_textcontent.setText(questionEntity.getTextcontent());

            }
        };
        qusetionModel.bindCallback(call, questionCallback);

    }

    private void initEvents() {
        answer_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        answer_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savadata();
            }
        });
        answer_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });
        answer_paly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                playvoice();
            }
        });

    }

    private void playvoice() {

        file = new File(voice_filePath);
        if (file.exists()) {
            player = MediaPlayer
                    .create(this, Uri.parse(file.getAbsolutePath()));
        } else {
            Toast.makeText(AnswerActivity.this, "没有文件", Toast.LENGTH_SHORT).show();

            return;
        }
        try {
            player.reset();
            player.setDataSource(file.getAbsolutePath());
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void savadata() {
        answerModel = new AnswerModel();
        call = answerModel.insertanswer(
                sp.getString("user_id", ""),
                qid,
                answer_content.getText().toString());
        answerCallback = new RetrofitCallback<Status>() {
            @Override
            public void onResponse(Status status) {

//                if (status.getCode().toString().equals("1")){
//                    Toast.makeText(AnswerActivity.this,"回答成功",Toast.LENGTH_SHORT).show();
////                    Intent intent=new Intent(AnswerActivity.this,QuestionContentActivity.class);
////                    intent.putExtra("qid",qid);
////                    startActivity(intent);
//                    finish();
//                }
//                else{
//                    Toast.makeText(AnswerActivity.this,"回答失败",Toast.LENGTH_SHORT).show();
//
//                }

            }
        };
        answerModel.bindCallback(call, answerCallback);
        finish();

    }

    private void initViews() {
        sp = getSharedPreferences("userinfo", MODE_PRIVATE);
        intent = getIntent();
        qid = intent.getStringExtra("qid");
        answer_return = (ImageView) findViewById(R.id.answer_return);
        answer_description = (TextView) findViewById(R.id.answer_description);
        answer_textcontent = (TextView) findViewById(R.id.answer_textcontent);
        answer_content = (EditText) findViewById(R.id.answer_content);
        answer_voice = (ImageView) findViewById(R.id.answer_voice);
        answer_location = (ImageView) findViewById(R.id.answer_location);
        answer_locationtext = (TextView) findViewById(R.id.answer_locationtext);
        answer_send = (ImageView) findViewById(R.id.answer_send);
        answer_paly = (Button) findViewById(R.id.answer_paly);
        answer_paly.setVisibility(View.GONE);
    }


    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        if (null == locationOption) {
            locationOption = new AMapLocationClientOption();
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        }
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }


    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                  /*  sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");*/
                    //sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    sb.append(location.getPoiName() + "\n");
                    //定位完成的时间
                    // sb.append("定位时间: " + MapUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                //定位之后的回调时间
                //sb.append("回调时间: " + MapUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                answer_locationtext.setText(result);
            } else {
                answer_locationtext.setText("定位失败，loc is null");
            }
        }
    };

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    // 根据控件的选择，重新设置定位参数
    private void resetOption() {
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(true);
        // 设置是否开启缓存
        locationOption.setLocationCacheEnable(true);
        // 设置是否单次定位
        locationOption.setOnceLocation(true);
        //设置是否等待设备wifi刷新，如果设置为true,会自动变为单次定位，持续定位时不要使用
        locationOption.setOnceLocationLatest(true);
        //设置是否使用传感器
        locationOption.setSensorEnable(true);
        //设置是否开启wifi扫描，如果设置为false时同时会停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        String strInterval = "";
        if (!TextUtils.isEmpty(strInterval)) {
            try {
                // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
                locationOption.setInterval(Long.valueOf(strInterval));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        String strTimeout = "";
        if (!TextUtils.isEmpty(strTimeout)) {
            try {
                // 设置网络请求超时时间
                locationOption.setHttpTimeOut(Long.valueOf(strTimeout));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

}
